#!/usr/bin/env python
# -*- coding: utf-8 -*-

import logging
import time
import codecs
import sys
import json
from gate_api import FuturesApi, FuturesOrder, ApiClient, Configuration
import futures_toolbox

from config import RunConfig
from gate_api.exceptions import GateApiException


# from gate_api import (
#     ApiClient,
#     Configuration,
#     FuturesApi,
#     FuturesOrder,
#     Transfer,
#     WalletApi,
# )


class YYGateWangge:
    def __init__(
        self,
        contract,
        singleAmount,
        interval,
        apiKey,
        apiSecret,
        hostUsed,
        transactionPoint=0.004,
    ):
        self.__settle = "usdt"  # 市场
        self.__interval = interval  # 深度 eg."0.0001"
        self.__contract = contract  # 交易对
        self.__initPrice = 0  # 计算买入和卖出的基础价格
        self.__lastPrice = 0  # 最后一次交易价格
        self.__transactionPoint = (
            transactionPoint  # 交易点（即下跌或上升多少 买入或卖出）,default : 0.004
        )
        self.__singleAmount = singleAmount  # 单笔交易量

        # API管理工具
        config = Configuration(key=apiKey, secret=apiSecret, host=hostUsed)
        futures_api = FuturesApi(ApiClient(config))
        self.__futures_api = futures_api


        # # 设置编码为utf-8
        # sys.stdout = codecs.getwriter("utf-8")(sys.stdout.detach())

        # 日志文件索引
        self.__dateDict = {}
        self.__lastLoggerHandler = None
        # 日志
        #   单日日志
        date = time.strftime("%Y-%m-%d")

        self.__logger = logging.getLogger(__name__)
        self.__logger.setLevel(level=logging.INFO)
        self.updateLoggerFile()
        #   总日志
        handlerName = str("%s.log" % (__name__))
        handler_total = logging.FileHandler(
            handlerName, encoding="utf-8"
        )
        handler_total.name = handlerName
        formatter_total = logging.Formatter("%(filename)s [%(asctime)s] %(message)s")
        handler_total.setFormatter(formatter_total)
        if self.check_file_handler_exists(self.__logger, handler_total):
            print("特定的 FileHandler 已经存在")  
        else:  
            self.__logger.addHandler(handler_total)
            print("特定的 FileHandler 不存在")

        # 开始网格交易
        self.startSeeDealChance()

    #    开始寻找交易机会
    def startSeeDealChance(self):

        # while 1:
        #     time.sleep(1)
        # 检查是否需要更新log文件
        self.updateLoggerFile()
        # 获取买一价格和卖一价格

        try:
            list_fututes = self.__futures_api.list_futures_order_book(
                self.__settle,
                self.__contract,
                limit=1,
                interval=self.__interval,
                async_req=True,
            )
        except:
            self.__logger.error("网络异常")
            return
        
        if list_fututes == None:
            print("返回的是None")
            return
        
        try:
            asks = list_fututes.get().asks
            bids = list_fututes.get().bids
        except:
            self.__logger.error("网络异常了")
            return
        
        if len(bids) == 0:
            return
        if len(asks) == 0:
            return
        depthBuyOnePrice = float(bids[0].p)
        depthSellOnePrice = float(asks[0].p)

        # self.__logger.info("买一价格：%g,卖一价格：%g",depthBuyOnePrice,depthSellOnePrice)
        # 初始化各值
        if self.__initPrice == 0:
            self.__initPrice = depthBuyOnePrice
            self.__lastPrice = self.__initPrice
            print(
                "%s 起始价=%g 最后交易价=%g"
                % (self.__contract, self.__initPrice, self.__lastPrice)
            )
            self.updateNextPrice()

        # depth_length = len(self.__interval)
        # price = str(self.__nextSellPrice)
        # price = price[0:depth_length]
        # count = self.__singleAmount * -1
        # print('空单进来了: %s ,count: %d' % (price, count))

        # futures_order = FuturesOrder(contract=self.__contract,size=count)
        # futures_order.price = price
        # futures_order.contract = self.__contract
        # order_response = self.__futures_api.create_futures_order(self.__settle, futures_order)

        # self.__lastPrice = self.__nextSellPrice
        # self.__logger.info('(空) 价格：%g, 数量：%f, response: %s' % (self.__nextSellPrice, self.__singleAmount, order_response))
        # self.updateNextPrice()

        # return

        depth_length = len(self.__interval)

        # 检查买入机会
        if depthSellOnePrice <= self.__nextBuyPrice:
            # buyReust = '注释交易'
            # buyReust = self.__OKFuture.future_trade(self.__symbol, 'quarter', self.__nextBuyPrice,
            #                                       self.__singleAmount, '1', '0', self.__leverRate)
            # buyReust = HuobiServices.send_order(self.__singleAmount,'api',self.__symbol,'buy-limit', self.__nextBuyPrice)
            # buyReust = FuturesOrder(contract=self.__contract, size=self.__singleAmount)

            price = f"{self.__nextBuyPrice:.{depth_length-2}f}"

            futures_order = FuturesOrder(
                contract=self.__contract, size=self.__singleAmount
            )
            futures_order.price = price
            futures_order.contract = self.__contract
            try:
                order_response = self.__futures_api.create_futures_order(
                    self.__settle, futures_order
                )
            except:
                self.__logger.error("网络异常")
                return
            self.__lastPrice = self.__nextBuyPrice
            # self.__logger.info(
            #     "(%s_buy) price: %s, count: %f, response: %s"
            #     % (self.__contract ,price, self.__singleAmount, order_response)
            # )
            self.saveRecord(order_response, False)

            self.updateNextPrice()
            return

        # 检查卖出机会
        if depthBuyOnePrice >= self.__nextSellPrice:
            # self.__logger.info('空单进来了:%g',self.__nextSellPrice)
            # sellReust = '注释交易'
            # sellReust = self.__OKFuture.future_trade(self.__symbol, 'quarter', self.__nextSellPrice, self.__singleAmount, '3', '0', self.__leverRate)
            # sellReust = HuobiServices.send_order(self.__singleAmount,'api',self.__symbol,'sell-limit', self.__nextSellPrice)
            # todo

            price = f"{self.__nextSellPrice:.{depth_length-2}f}"
            count = self.__singleAmount * -1

            futures_order = FuturesOrder(contract=self.__contract, size=count)
            futures_order.price = price
            futures_order.contract = self.__contract
            try:
                order_response = self.__futures_api.create_futures_order(
                    self.__settle, futures_order
                )
            except:
                self.__logger.error("网络异常")
                return
            
            self.__lastPrice = self.__nextSellPrice
            # self.__logger.info(
            #     "(%s_sell) price: %s, count: %f, response: %s"
            #     % (self.__contract ,price, self.__singleAmount, order_response)
            # )
            self.saveRecord(order_response, True)
            self.updateNextPrice()
            return

    # 更新下次交易价格
    def updateNextPrice(self):

        # 计算网格比例
        rate = futures_toolbox.calculateWGPriceRate(
            self.__contract,
            self.__lastPrice,
            self.__singleAmount,
            0.3,
            0.004)
        
        self.__transactionPoint = rate
        print("%s 网格比例：%f" % (self.__contract, self.__transactionPoint))

        self.__nextBuyPrice = (
            self.__lastPrice - self.__lastPrice * self.__transactionPoint
        )
        self.__nextSellPrice = (
            self.__lastPrice + self.__lastPrice * self.__transactionPoint
        )
        print(
            "%s 卖一价到 %g 买，买一价到 %g 卖"
            % (self.__contract, self.__nextBuyPrice, self.__nextSellPrice)
        )
    def check_file_handler_exists(self, logger, file_handler):  
        for handler in logger.handlers:  
            if handler.name == file_handler.name:  
                return True  
        return False  

    def updateLoggerFile(self):

        # 日志
        date = time.strftime("%Y-%m-%d")
        if date in self.__dateDict:
            return
        # print(self.__dateDict)

        if self.__lastLoggerHandler is not None:
            # print("handle: %s" % self.__lastLoggerHandler)
            self.__logger.removeHandler(self.__lastLoggerHandler)

        self.__dateDict[date] = date
        handlerName = str("%s_%s.log" % (__name__, date))
        handler = logging.FileHandler(
            handlerName, encoding="utf-8"
        )
        handler.name = handlerName
        formatter = logging.Formatter("%(filename)s [%(asctime)s] %(message)s")
        handler.setFormatter(formatter)
        self.__lastLoggerHandler = handler

        if self.check_file_handler_exists(self.__logger, handler):
            print("特定的 FileHandler 已经存在")  
        else:  
            self.__logger.addHandler(handler)
            print("特定的 FileHandler 不存在")

    def saveRecord(self, order_response, issell):
        """记录交易详情
        :param dict order_response: 订单创建返回详情 (required)
        :param bool issell: 交易方向 (required)
        """
        dict = order_response.to_dict()
        if issell:
            order_type = "SELL"
        else:
            order_type = "BUY"
        record_json = json.dumps(dict)
        # self.__logger.info
        self.__logger.info(
                "(%s_%s), response: %s"
                % (self.__contract , order_type, record_json)
            )

